package com.demo.controller.menu;

import com.demo.util.ConfigLoader;
import com.demo.util.ControllerManager;
import com.demo.util.EmailSender;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;

public class ConfigController implements Initializable {
    @FXML
    private TextField hostField;
    @FXML
    private TextField portField;
    @FXML
    private TextField usernameField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private CheckBox starttlsField;

    private Stage stage;
    private Properties properties;

    public void setStage(Stage stage) {
        this.stage = stage;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
        loadProperties();
    }

    private void loadProperties() {
        hostField.setText(properties.getProperty("mail.smtp.host"));
        portField.setText(properties.getProperty("mail.smtp.port"));
        usernameField.setText(properties.getProperty("mail.smtp.username"));
        passwordField.setText(properties.getProperty("mail.smtp.password"));
        starttlsField.setSelected(properties.getProperty("mail.smtp.starttls.enable").equals("true"));
    }

    @FXML
    private void handleSave() {
        String configFilePath = ConfigLoader.configFile.getPath();
        try {
            PropertiesConfiguration config = new PropertiesConfiguration(configFilePath);
            config.setAutoSave(true);
            config.setProperty("mail.smtp.host", hostField.getText());
            config.setProperty("mail.smtp.port", portField.getText());
            config.setProperty("mail.smtp.username", usernameField.getText());
            config.setProperty("mail.smtp.password", passwordField.getText());
            config.setProperty("mail.smtp.starttls.enable", starttlsField.isSelected() ? "true" : "false");
        } catch (ConfigurationException e) {
            new Alert(Alert.AlertType.ERROR, "保存配置失败：" + e.getMessage()).showAndWait();
        }
        new Alert(Alert.AlertType.INFORMATION, "配置保存成功！").showAndWait();

        // 重新加载配置文件
        ConfigLoader.loadConfig();
        // 重新创建新的邮件发送会话
        EmailSender.createSession();
        // 刷新底部状态栏显示
        ControllerManager.footerController.refreshStatus();
        stage.close();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        ControllerManager.configController = this;
    }

    @FXML
    private void handleClose() {
        stage.close();
    }
}